package com.whmnx.my.ui.viewmodel;

import android.app.Application;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.whmnx.base.bean.LoginBean;
import com.whmnx.base.bean.PrivateBean;
import com.whmnx.base.constants.Constants;
import com.whmnx.base.constants.EventConstants;
import com.whmnx.base.http.CallBack;
import com.whmnx.base.http.HttpClient;
import com.whmnx.base.view.CommonDialog2;
import com.whmnx.my.R;
import com.whmnx.my.databinding.FragmentAddLoctionBinding;
import com.whmnx.my.ui.activity.LocationActiviy;
import com.whmnx.my.ui.fragment.MyAddLoctionFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.goldze.mvvmhabit.utils.Utils;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * author : huang
 * date   : 2020/9/15 0015 18:57
 * version: 1.0
 * @author Administrator
 */
public class AddLocModel extends ToolbarViewModel {

    public ObservableField<String> Address_Name  = new ObservableField<>("");

    public ObservableField<String> Address_Mobile  = new ObservableField<>("");

    public ObservableField<String> Address_Detailed  = new ObservableField<>("");

    public ObservableField<String> Address_Label  = new ObservableField<>("");
    private String province2;
    private String address_value;

    private Disposable subscribe;
    private String string;


    public AddLocModel(@NonNull Application application) {
        super(application);
    }

    private MyAddLoctionFragment mFragment;
    private FragmentAddLoctionBinding mbinding;

    public void initToolbar(MyAddLoctionFragment myAddLoctionFragment, FragmentAddLoctionBinding binding) {
        this.mFragment = myAddLoctionFragment;
        this.mbinding = binding;
        setTitleText("新增地址");
        setRightText("完成");
        setRightTextVisible(View.VISIBLE);
        initView();
        if (mFragment.addressBean != null){
            Address_Name.set(mFragment.addressBean.getAddress_Name());
            Address_Mobile.set(mFragment.addressBean.getAddress_Mobile());
            Address_Label.set(mFragment.addressBean.getAddress_Detailed());
            if (!TextUtils.isEmpty(mFragment.addressBean.getAddress_LabelDetail())){
                Address_Detailed.set(mFragment.addressBean.getAddress_LabelDetail());
            }

            if (mFragment.addressBean.getAddress_State() == 0){
                mbinding.cb.setChecked(true);
            }
        }
    }

    private void initView() {
        subscribe = RxBus.getDefault().toObservable(String.class)
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String object){
                        if (object.contains(EventConstants.MAP)){
                            string = object.split(",")[1];
                            Address_Label.set(string.split("-")[2]);
                        }
                    }
                });
        RxSubscriptions.add(subscribe);
    }

    //新增地址
    public BindingCommand delOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            String s2 = "是否删除";
            new CommonDialog2(mFragment.getActivity(), R.style.dialog, s2,"", (dialog, confirm) -> {
                if (confirm) {
                    Map<String, Object> params = new HashMap<>();
                    List<String> list = new ArrayList<>();
                    list.add(mFragment.addressBean.getAddress_Id());
                    params.put("",list);

                    HttpClient.post(mFragment.getActivity(), Constants.DELETE2, params,new CallBack<LoginBean>() {
                        @Override
                        public void onSuccess(LoginBean result) {
                            RxBus.getDefault().post(EventConstants.ADDRESS);
                            finish();
                        }
                    });
                }
                dialog.dismiss();
            }).show();
        }
    });



    //新增地址
    public BindingCommand OnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            hideInput();
            startActivity(LocationActiviy.class);


            //申明对象
         /*   CityPickerView mPicker = new CityPickerView();
            //预先加载仿iOS滚轮实现的全部数据（oncreate()中）
            mPicker.init(mFragment.getActivity());

            //配置
            CityConfig cityConfig = new CityConfig.Builder()
                    .title("选择城市")//标题
                    .titleTextSize(16)//标题文字大小
                    .titleTextColor("#585858")//标题文字颜  色
                    .titleBackgroundColor("#ffdddddd")//标题栏背景色
                    .confirTextColor("#ffe1163c")//确认按钮文字颜色
                    .confirmText("确定")//确认按钮文字
                    .confirmTextSize(14)//确认按钮文字大小
                    .cancelTextColor("#585858")//取消按钮文字颜色
                    .cancelText("取消")//取消按钮文字
                    .cancelTextSize(14)//取消按钮文字大小
                    .setCityWheelType(CityConfig.WheelType.PRO_CITY_DIS)//显示类，只显示省份一级，显示省市两级还是显示省市区三级
                    .showBackground(true)//是否显示半透明背景
                    .visibleItemsCount(7)//显示item的数量
                    .province("湖北省")//默认显示的省份
                    .city("武汉市")//默认显示省份下面的城市
                    .district("洪山区")//默认显示省市下面的区县数据
                    .provinceCyclic(true)//省份滚轮是否可以循环滚动
                    .cityCyclic(true)//城市滚轮是否可以循环滚动
                    .districtCyclic(true)//区县滚轮是否循环滚动
                    .setCustomItemLayout(R.layout.item_city)//自定义item的布局
                    .setCustomItemTextViewId(R.id.item_city_name_tv)//自定义item布局里面的textViewid
                    .drawShadows(true)//滚轮不显示模糊效果
                    .setLineHeigh(1)//中间横线的高度
                    .setLineColor("#ffe1163c")
                    .setShowGAT(true)//是否显示港澳台数据，默认不显示
                    .build();
            //添加配置
            mPicker.setConfig(cityConfig);
            //显示
            mPicker.showCityPicker();
            //监听选择点击事件及返回结果
            mPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
                @Override
                public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                    super.onSelected(province, city, district);
                    address_value = province.getId() + "," + city.getId() + "," + district.getId();
                    //为TextView赋值
                    Address_Label.set(province + "" + city + "" + district);
                   // getCascadersource();
                }

                @Override
                public void onCancel() {
                    super.onCancel();
                }
            });*/
        }
    });

    private void getCascadersource() {
        Map<String, Object> params = new HashMap<>();
        params.put("parentId","0");
        HttpClient.get(Utils.getContext(), Constants.GETCASCADERSOURCE, params,new CallBack<List<PrivateBean>>() {
            @Override
            public void onSuccess(List<PrivateBean> privateBeans) {

            }
        });
    }

    private void hideInput() {
        InputMethodManager imm = (InputMethodManager) mFragment.getActivity().getSystemService(INPUT_METHOD_SERVICE);
        View v = mFragment.getActivity().getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }


    /**
     * 右边文字的点击事件，子类可重写
     */
    @Override
    protected void rightTextOnClick() {
        if (TextUtils.isEmpty(Address_Name.get())){
            ToastUtils.showShort("请输入收货人名字");
            return;
        }
        if (TextUtils.isEmpty(Address_Mobile.get())){
            ToastUtils.showShort("请输入收货人电话");
            return;
        }
     /*   if (TextUtils.isEmpty(Address_Label.get())){
            ToastUtils.showShort("请选择省市区");
            return;
        }*/
        if (TextUtils.isEmpty(Address_Label.get())){
            ToastUtils.showShort("请地图选择位置");
            return;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("address_Name",Address_Name.get());
        params.put("address_Mobile",Address_Mobile.get());
    //    params.put("address_Label",Address_Label.get());
        params.put("address_Detailed",Address_Label.get());

        params.put("Address_LabelDetail",Address_Detailed.get());
      //  params.put("Address_Value",address_value);
        if (!TextUtils.isEmpty(string)){
            params.put("Address_Lat",string.split("-")[0]);
            params.put("Address_Lng",string.split("-")[1]);
        }else {
            params.put("Address_Lat",mFragment.addressBean.getAddress_Lat());
            params.put("Address_Lng",mFragment.addressBean.getAddress_Lng());
        }

        params.put("Address_UserInfoId", SPUtils.getInstance().getString(Constants.USERID));
        if (mFragment.addressBean != null)
            params.put("address_Id", mFragment.addressBean.getAddress_Id());
        if (mbinding.cb.isChecked()){
            params.put("address_State",0);
        }else {
            params.put("address_State",1);
        }


                HttpClient.post(mFragment.getActivity(), Constants.ADDORUPDATE3, params,new CallBack<LoginBean>() {
            @Override
            public void onSuccess(LoginBean result) {
                RxBus.getDefault().post(EventConstants.ADDRESS);
                finish();
            }
        });
    }
}
